package com.ipay.wechat.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UploadUtil {
	private static Logger logger = LoggerFactory.getLogger(UploadUtil.class);

	/**
	 * 上传媒体文件
	 * 
	 * @param mediaId
	 *            媒体文件id
	 * @param request
	 * @param access_token
	 *            接口访问凭证
	 * @return
	 */
	public static String downloadMedia(String mediaId,
			HttpServletRequest request, String access_token, String mobile) {
		String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", access_token).replace(
				"MEDIA_ID", mediaId);
		HttpURLConnection conn = null;
        String savePath=savePath(request,mobile);
        String filePath;
		FileOutputStream fos=null;
		try {
			URL url = new URL(requestUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			
			if(!savePath.endsWith("/")){
				savePath+="/";
			}
			//根据内容类型获取扩展名
			String fileExt=getFileexpandedName(conn.getHeaderField("Content-Type"));
			//将mediaId作为文件名
			filePath=savePath+mediaId+fileExt;
			BufferedInputStream bis=new BufferedInputStream(conn.getInputStream());
			File filept = new File(filePath);
			fos=new FileOutputStream(filept);
			byte[] buf=new byte[8096];
			int size=0;
			while((size=bis.read(buf))!=-1){
				fos.write(buf,0,size);
			}
			fos.close();
			bis.close();
			
			conn.disconnect();
			String info=String.format("下载媒体文件成功，filepath="+filePath);
			logger.info(info);

		} catch (Exception e) {
			filePath=null;
			logger.info("下载媒体文件失败：", e);
		}finally {
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return filePath;
	}
    
	/**
	 * 根据内容类型判断文件扩展名
	 * @param contentType 内容类型
	 * @return
	 */
	public static String getFileexpandedName(String contentType) {
		String fileEndWitsh = "";
		if ("image/jpeg".equals(contentType))
			fileEndWitsh = ".jpg";
		else if ("audio/mpeg".equals(contentType))
			fileEndWitsh = ".mp3";
		else if ("audio/amr".equals(contentType))
			fileEndWitsh = ".amr";
		else if ("video/mp4".equals(contentType))
			fileEndWitsh = ".mp4";
		else if ("video/mpeg4".equals(contentType))
			fileEndWitsh = ".mp4";
		return fileEndWitsh;
	}

	public static String savePath(HttpServletRequest request, String mobile) {
		String realPath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "uploadImg" + File.separator + mobile;
		File fileLocation = new File(realPath);
		// 此处也可以在应用根目录手动建立目标上传目录
		if (!fileLocation.exists()) {
			boolean isCreated = fileLocation.mkdir();
			if (!isCreated) {
				// 目标上传目录创建失败,可做其他处理,例如抛出自定义异常等,一般应该不会出现这种情况。
				return null;
			} else {
				return realPath;
			}
		} else {
			return realPath;
		}

	}
}
